package com.itheima.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {

    //会话工厂全局只有一个
    private static SqlSessionFactory factory;

    private static ThreadLocal<SqlSession> local=new ThreadLocal<>();

    //初始化会话工厂
    static {
        initFactory();
    }
    private static void initFactory() {
        String resource="mybatis-config.xml";
        try(InputStream in = Resources.getResourceAsStream(resource);) {
            factory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取会话对象
     * @return
     */
    private static SqlSession getSession(){
        //从trheadLocal获取会话对象
        SqlSession sqlSession = local.get();
        if(sqlSession==null){
            sqlSession=factory.openSession();
            //将获取的会话对象存入local下
            local.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 获取代理对象的方法
     * @param type
     * @param <T>
     * @return
     */
    public static  <T> T getMapper(Class<T> type) {
        return getSession().getMapper(type);
    }

    /**
     * 释放资源
     */
    public static void close(){
        SqlSession sqlSession = local.get();
        if(sqlSession!=null){
            sqlSession.close();
            //防止内存泄露
            local.remove();
        }
    }

    /**
     * 事务提交
     */
    public static void commit(){
        SqlSession sqlSession = local.get();
        if(sqlSession!=null){
            sqlSession.commit();
        }
    }

    /**
     * 事务回滚
     */
    public static void rollback(){
        SqlSession sqlSession = local.get();
        if(sqlSession!=null){
            sqlSession.rollback();
        }
    }

}
